from flask import Flask, render_template, request, redirect, url_for, flash
from datetime import datetime
import sqlite3

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于保持会话安全

# 模拟数据库中的用户存储
users = {
    'admin': 'admin',
    'chen': '123456',
    'zhangsan': '456789',
    'zeng': 'abc'
}

# 默认用户权限
default_permissions = ['智慧党建', '综合办公', '学生一体化']

# 用户权限
permissions = {
    'admin': ['智慧党建', '综合办公', '项目运行', '教师一体化', '学生一体化'],
    'chen': ['智慧党建', '综合办公', '项目运行', '教师一体化', '学生一体化'],
    'zhangsan': default_permissions,
    'zeng': ['智慧党建', '综合办公', '项目运行', '教师一体化', '学生一体化']
}

# 初始化数据库和表
def init_db():
    conn = sqlite3.connect('login_records.db')
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS login_records (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT NOT NULL,
            login_time TEXT NOT NULL,
            ip TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()

init_db()

# 记录登录信息的函数
def log_login(username, ip, is_password_correct):
    conn = sqlite3.connect('login_records.db')
    c = conn.cursor()
    if is_password_correct:
        c.execute('''
            INSERT INTO login_records (username, login_time, ip) VALUES (?, ?, ?)
        ''', (username, datetime.now().strftime('%Y-%m-%d %H:%M:%S'), ip))
    else:
        c.execute('''
            INSERT INTO login_records (username, login_time, ip) VALUES (?, ?, ?)
        ''', (f"{username} 输入密码错误", datetime.now().strftime('%Y-%m-%d %H:%M:%S'), ip))
    conn.commit()
    conn.close()

@app.route('/')
def index():
    return render_template('login.html')

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    # 验证用户名和密码
    if username in users and users[username] == password:
        # 用户登录成功，记录登录信息
        log_login(username, request.remote_addr, True)
        return redirect(url_for('success', username=username))
    else:
        # 用户登录失败，记录登录信息
        log_login(username, request.remote_addr, False)
        flash('用户名或密码错误！')
        return redirect(url_for('index'))

@app.route('/success/<username>')
def success(username):
    # 确保用户名存在于用户数据库中
    if username in users:
        # 传递权限列表给模板
        return render_template('dashboard.html', username=username, user_permissions=permissions.get(username, default_permissions))
    else:
        flash('用户名不存在！')
        return redirect(url_for('index'))

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        # 检查用户名是否已存在
        if username in users:
            flash('用户名已存在')
            return render_template('register.html')
        else:
            # 添加新用户到模拟数据库，并设置默认权限
            users[username] = password
            flash('注册成功，请登录！')
            return redirect(url_for('index'))
    else:
        return render_template('register.html')

@app.route('/welcome')
def welcome():
    return render_template('welcome.html')

@app.route('/view-records')
def view_records():
    conn = sqlite3.connect('login_records.db')
    c = conn.cursor()
    c.execute('SELECT * FROM login_records')
    records = c.fetchall()
    conn.close()
    return render_template('view_records.html', records=records)

if __name__ == '__main__':
    app.run(debug=True)